package com.example.ruiji.controller.category;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.ruiji.dao.mapper.CategoryMapper;
import com.example.ruiji.dao.mapper.TagMapper;
import com.example.ruiji.pojo.Category;
import com.example.ruiji.pojo.Ltag;
import com.example.ruiji.service.category.CategoryServiceImpl;
import com.example.ruiji.service.ltag.LtagServiceImpl;
import com.example.ruiji.utils.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Author:BaiYiChen
 * Date:2022/5/1 20:22
 *
 * @author BaiYiChen
 */
@RestController
@RequestMapping(value = "/category")
public class CategoryController {
  @Autowired
  private CategoryServiceImpl categoryService;
  @Autowired
  private LtagServiceImpl ltagService;
  @GetMapping("/av/{aId}")
  public void getCategoryAvatar(@PathVariable("aId")Integer id, HttpServletResponse resp) throws IOException {
    Category category = categoryService.findCategoryById(id);
    byte[] avatar = category.getAvatar();
    
    resp.setContentType("image/jpeg");
    resp.setCharacterEncoding("UTF-8");
    
    OutputStream outputStream = resp.getOutputStream();
    InputStream inputStream = new ByteArrayInputStream(avatar);
    
//    创建一个写buffer区，每次写1024byte
    int len=0;
    byte[] buffer = new byte[1024];
    
    while((len=inputStream.read(buffer, 0, 1024))!=-1){
      outputStream.write(buffer, 0, len);
    }
    outputStream.flush();
    outputStream.close();
  }
  @GetMapping("/tag/{aId}")
  public void getTagAvatar(@PathVariable("aId")Integer id, HttpServletResponse resp) throws IOException {
    Ltag ltag = ltagService.findLtagById(id);
    byte[] avatar = ltag.getAvatar();
    
    resp.setContentType("image/jpeg");
    resp.setCharacterEncoding("UTF-8");
    
    OutputStream outputStream = resp.getOutputStream();
    InputStream inputStream = new ByteArrayInputStream(avatar);

//    创建一个写buffer区，每次写1024byte
    int len=0;
    byte[] buffer = new byte[1024];
    
    while((len=inputStream.read(buffer, 0, 1024))!=-1){
      outputStream.write(buffer, 0, len);
    }
    outputStream.flush();
    outputStream.close();
  }
}
